/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Plano;

import Geral.ErroInternoException;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author Ivaldo
 */
@Stateless
public class RepositorioPlanoJPA implements IRepositorioPlano, Serializable {
    
    @PersistenceContext
    private EntityManager em;
    
    public RepositorioPlanoJPA(){
        this.em = Persistence.createEntityManagerFactory("HelpFitPU").createEntityManager();
    }
    
    @Override
    public void adicionar(Plano plano) throws ErroInternoException, PlanoExistenteException {
        try{
            this.em.persist(plano);
        }catch(Exception e){
            throw new ErroInternoException(e);
        }
    }

    @Override
    public void remover(long id_plano) throws ErroInternoException, PlanoInexistenteException {
        Plano plano = buscarPlano(id_plano);
        try{
            this.em.remove(plano);
        }catch(Exception e){
            throw new ErroInternoException(e);
        }
    }

    @Override
    public Plano buscarPlano(long id_plano) throws ErroInternoException, PlanoInexistenteException {
        try{
            Plano plano = this.em.find(Plano.class, id_plano);
            if(plano == null){
                throw new PlanoInexistenteException();
            }
            return plano;
        }catch(PlanoInexistenteException ex){
            throw ex;
        }catch(Exception e){
            throw new ErroInternoException(e);
        }
    }

    @Override
    public void atualizar(Plano plano) throws ErroInternoException, PlanoInexistenteException {
        buscarPlano(plano.getId());
        try{
            this.em.merge(plano);
        }catch(Exception e){
            throw new ErroInternoException(e);
        }
    }

    @Override
    public List<Plano> listaPlano(Plano plano) throws ErroInternoException {
        try{
            TypedQuery<Plano> listaPlano = this.em.createQuery("select * from plano ", Plano.class);
            if(listaPlano.getResultList().isEmpty()){
                throw new PlanoInexistenteException();
            }
            return listaPlano.getResultList();
        }catch(Exception e){
            throw new ErroInternoException(e);
        }
    }
    
}
